<?php
defined('IN_LK') or die('Access Denied');
class session_mysql
{
	private static $db = null;
	private $lifetime = SESSION_LIFE;
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		self::$db = is_resource(self::$db) ? self::$db : lk::load_model('session');
		session_set_save_handler(array(&$this,'open'), 
								 array(&$this,'close'), 
								 array(&$this,'read'), 
								 array(&$this,'write'), 
								 array(&$this,'destroy'), 
								 array(&$this,'gc'));
    	session_start();
	}
	
	/**
	 * 删除过期的 session
	 * @param int $ttl 生命周期
	 * @return bool
	 */
	public function gc($ttl)
	{
		$expiretime = TIME - $ttl;
		return self::$db->delete("`lastvisit`<'$expiretime'");
	}
	
	/**
	 * session_set_save_handler  open方法
	 * @param $save_path
	 * @param $session_name
	 * @return true
	 */
	public function open($save_path, $session_name)
	{
		return true;
	}
	
	/**
	 * session_set_save_handler  close方法
	 * @return bool
	 */
    public function close()
	{
        return $this->gc($this->lifetime);
    } 
	
	/**
	 * session_set_save_handler  read方法
	 * @param  string $sid  session_id
	 * @return string      读取session_id
	 */
    public function read($sid)
	{
		$res = self::$db->get_one('data', "`session_id`='$sid'");
		return $res ? $res['data'] : false;
    }
	
	/**
	 * 写入session_id
	 * 
	 */
	public function write($sid, $data)
	{
		$userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 0;
    	$roleid = isset($_SESSION['roleid']) ? $_SESSION['roleid'] : 0;
    	$groupid = isset($_SESSION['groupid']) ? $_SESSION['groupid'] : 0;
		$m = defined('M') ? M : '';
		$c = defined('C') ? C : '';
		$a = defined('A') ? A : '';
		if(strlen($data) > 255)
		{
			$data = '';
		}
		$ip = get_ip();
		$sessiondata = array(
					'session_id' => $sid,
					'userid'     => $userid,
					'ip'         => $ip,
					'lastvisit'  => TIME,
					'roleid'     => $roleid,
					'groupid'    => $groupid,
					'm'          => $m,
					'c'          => $c,
					'a'          => $a,
					'data'       => $data,
				);
		return self::$db->insert($sessiondata, true);
	}
	
	/** 
	 * 删除指定的session_id
	 * @param $id session
	 * @return bool
	 */
    public function destroy($sid)
	{
		return self::$db->delete("`session_id`='$sid'");
    }
}